package org.groupg.mockdatabyspring.morkdata.service.runnables;

import cn.hutool.core.io.FileUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import org.groupg.mockdatabyspring.morkdata.model.enums.MarkDataConfig;

import java.io.File;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;


/**
 * 项目的生产者，处理过程中主要在文件行数过多时，将文件分解成多个文件，完成处理内容。
 * @author Cashgift Li
 */
public class DataFileProducer implements Callable<File> {
    private static final Log log = LogFactory.get();

    private final BlockingQueue<File> taskProducerQueue;

    private final int fileNum;

    private final File file;

    private final CountDownLatch latch;

    /**
     * 默认初始化方法
     * @param taskProducerQueue 生产者要生产内容的队列
     * @param fileNum 文件的数量
     * @param file 原始文件
     * @param latch 生产者的锁
     */
    public DataFileProducer(BlockingQueue<File> taskProducerQueue, int fileNum, final File file, CountDownLatch latch) {
        this.taskProducerQueue = taskProducerQueue;
        this.fileNum = fileNum;
        this.file = file;
        this.latch = latch;
    }

    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     */
    @Override
    public File call() {
        String fileName = file.getName();
        String tmpFilePath = MarkDataConfig.TMPFILEPATH;
        File tmpFile = FileUtil.createTempFile(FileUtil.file(tmpFilePath));
        log.debug("为文件：【{}】生成了第【{}】个文件，文件路径为：【{}】", fileName, (fileNum+1), tmpFile.getAbsolutePath());
        try {
            taskProducerQueue.put(tmpFile);
        } catch (InterruptedException e) {
            log.error(e, e.getMessage());
        }finally {
            latch.countDown();
        }
        return tmpFile;
    }
}
